package com.lvfuyang.commonproject.service.impl;

import com.lvfuyang.commonproject.common.BusinessException;
import com.lvfuyang.commonproject.dto.LoginRequest;
import com.lvfuyang.commonproject.entity.User;
import com.lvfuyang.commonproject.mapper.UserMapper;
import com.lvfuyang.commonproject.service.AuthService;
import com.lvfuyang.commonproject.service.CryptoService;
import com.lvfuyang.commonproject.util.JwtUtil;
import com.lvfuyang.commonproject.util.MD5Util;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务实现类
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CryptoService cryptoService;


    @Override
    public Map<String, Object> login(LoginRequest request) {
        // 参数校验
        if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
            throw new BusinessException("用户名和密码不能为空");
        }

        // RSA解密密码
        String plainPassword;
        try {
            plainPassword = cryptoService.decryptPassword(request.getPassword());
        } catch (Exception e) {
            log.error("密码解密失败", e);
            throw new BusinessException("密码格式错误");
        }

        // 查询用户
        User user = userMapper.selectByUsername(request.getUsername());
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 验证密码
        String encryptedPassword = MD5Util.encrypt(plainPassword);
        if (!encryptedPassword.equals(user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 检查用户状态
        if (!user.getIsActive()) {
            throw new BusinessException("用户已被禁用");
        }

        if (user.getIsDelete()) {
            throw new BusinessException("用户不存在");
        }

        // 查询用户权限信息
        User userWithAuthority = userMapper.selectUserWithAuthorityByUuid(user.getUuid());

        // 生成Token
        String token = JwtUtil.generateToken(user.getUuid(), user.getUsername());

        // 构造返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("uuid", userWithAuthority.getUuid());
        userInfo.put("username", userWithAuthority.getUsername());
        userInfo.put("authorityName", userWithAuthority.getAuthorityName());
        userInfo.put("gender", userWithAuthority.getGender());
        userInfo.put("phone", userWithAuthority.getPhone());

        result.put("user", userInfo);

        return result;
    }

    @Override
    public void logout(String token) {
        // 这里可以实现Token黑名单机制
        // 目前暂时不做处理
        log.info("用户登出，token: {}", token);
    }

    @Override
    public String refreshToken(String token) {
        // 验证当前Token
        if (!JwtUtil.validateToken(token)) {
            throw new BusinessException("Token无效");
        }

        // 获取用户ID
        String userId = JwtUtil.getUserIdFromToken(token);
        String username = JwtUtil.getUsernameFromToken(token);

        // 生成新Token
        return JwtUtil.generateToken(userId, username);
    }

    @Override
    public User getUserByToken(String token) {
        if (!JwtUtil.validateToken(token)) {
            throw new BusinessException("Token无效");
        }

        String userId = JwtUtil.getUserIdFromToken(token);
        return userMapper.selectUserWithAuthorityByUuid(userId);
    }

    @Override
    public boolean validateToken(String token) {
        return JwtUtil.validateToken(token);
    }

    /**
     * 能够获取到user信息
     *
     * @return
     */
    @Override
    public User getCurrentUser() {
        try {
            // 从当前请求上下文中获取Token
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            String authorization = request.getHeader("Authorization");
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                throw new BusinessException("未找到有效的认证信息");
            }

            String token = authorization.replace("Bearer ", "");
            return getUserByToken(token);

        } catch (Exception e) {
            log.error("获取当前用户失败", e);
            throw new BusinessException("获取当前用户失败");
        }
    }
} 
